package com.backend.teamapi.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import com.backend.teamapi.model.User;
import com.backend.teamapi.repository.UserRepository;

@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    // 注册用户
    public User register(User user) {
        // 校验格式
        validateUsernameAndPassword(user.getUsername(), user.getPassword());

        // 密码确认校验
        if (!user.getPassword().equals(user.getConfirmPassword())) {
            throw new IllegalArgumentException("密码和确认密码不匹配");
        }

        // 加密密码
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        user.setConfirmPassword(null);
        return userRepository.save(user);
    }

    // 登录验证
    public User login(String username, String password) {
        // 校验格式
        validateUsernameAndPassword(username, password);

        User user = userRepository.findByUsername(username);
        if (user != null && passwordEncoder.matches(password, user.getPassword())) {
            return user;
        }
        return null;
    }

    // 校验用户名和密码的格式
    private void validateUsernameAndPassword(String username, String password) {
        if (username == null || password == null) {
            throw new IllegalArgumentException("用户名或密码不能为空");
        }

        if (!username.matches("^[a-zA-Z0-9_][^\\s]*$")) {
            throw new IllegalArgumentException("用户名只能以字母、数字或下划线开头，不能包含空格");
        }

        if (password.length() < 6 || password.length() > 12 || password.contains(" ")) {
            throw new IllegalArgumentException("密码必须为6-12位，且不能包含空格");
        }
    }

    // 注销用户
    public void deleteUserById(Long id) {
        userRepository.deleteById(id);
    }
}
